<template>
    <div>
     <div>
<el-form :model="search" style=" margin: 20px 0 0 20px;" ref="search" label-width="100px">
  <el-row>
    <el-col :span="6" style=" margin-right: 20px;">
      <el-form-item label="盘点单号">
        <el-input v-model="search.code" placeholder="请输入" style="width: 100%;"/>
      </el-form-item>
    </el-col>
    <el-col :span="6">
      <el-form-item label="盘点结果">
        <el-select v-model="search.result" placeholder="请选择" style="width: 100%;">
          <el-option label="无盈亏" value="1"></el-option>
          <el-option label="有盈亏" value="2"></el-option>
        </el-select>
      </el-form-item>
    </el-col>
    <el-col :span="6">
      <el-form-item label="盘点类型">
        <el-select v-model="search.type" placeholder="请选择" style="width: 100%;">
          <el-option label="初期盘点" value="1"></el-option>
          <el-option label="存货盘点" value="2"></el-option>
          <el-option label="期末盘点" value="3"></el-option>
        </el-select>
      </el-form-item>
    </el-col>
    <el-col :span="2">
      <el-button class="cz" type="primary" @click="clear()">重置</el-button>
    </el-col>
    <el-col :span="2">
      <el-button class="cx" type="primary" @click="query()">查询</el-button>
    </el-col>
  </el-row>
</el-form>
</div>
<div style="display: flex;">
<div><el-button class="cx" type="primary" style="margin-left:20px;" @click="handleAdd">新增</el-button></div>
<div><el-button class="cx" type="primary" style="margin-left:20px;" @click="handleShen">审核</el-button></div>
<!-- <div><el-button class="cx" type="primary" style="margin-left:20px;" @click="handleChe">撤回</el-button></div> -->
<div><el-button class="cx" type="primary" style="margin-left:20px;" @click="handleCang">仓库锁定</el-button></div>
</div>
<div id="dataDiv">
      <el-table :data="data" class="bian"  @selection-change="handleSelectionChangeDel">
      <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" prop="i_iid"></el-table-column>
        <el-table-column label="盘点单号" prop="i_icode"></el-table-column>
        <!-- <el-table-column label="盘点结果" prop="i_iresult"></el-table-column> -->
        <el-table-column label="盘点结果"><template v-slot:default="scope">{{ scope.row.i_iresult === 1 ? '无盈亏' :  (scope.row.i_iresult === 2 ? '有盈亏' : '草稿') }}</template></el-table-column> 
        <el-table-column label="仓库名称" prop="i_iwid"></el-table-column>
        <el-table-column label="盘点类型"><template v-slot:default="scope">
          {{ scope.row.i_itype === 1 ? '初期盘点' :  (scope.row.i_itype === 2 ? '存货盘点' : (scope.row.i_itype === 3 ? '期末盘点' : '未知')) }}
         
        </template></el-table-column>
        <el-table-column label="审核状态">
          <template v-slot:default="scope">
            <span :style="{ color: getStatusColor(scope.row.i_ishen) }">
              {{ scope.row.i_ishen === 1 ? '未审核' :  (scope.row.i_ishen === 2 ? '已审核' : (scope.row.i_ishen === 3 ? '驳回' : '草稿')) }}
             
            </span>
        </template></el-table-column> 
        <el-table-column label="盘点开始时间" prop="i_istart_time"></el-table-column>
        <el-table-column label="盘点结束时间" prop="i_iend_time"></el-table-column>
        <el-table-column label="出库状态"><template v-slot:default="scope">{{ scope.row.i_ioutbound_status === 1 ? '未出库' :  (scope.row.i_ioutbound_status === 2 ? '部分出库' : (scope.row.i_ioutbound_status === 3 ? '已出库' : '未知')) }}</template></el-table-column> 
        <el-table-column label="入库状态"><template v-slot:default="scope">{{ scope.row.i_ientry_status === 1 ? '未入库' :  (scope.row.i_ientry_status === 2 ? '部分入库' : (scope.row.i_ientry_status === 3 ? '已入库' : '未知')) }}</template></el-table-column> 
        <el-table-column label="盘点货品" prop="i_igoods"></el-table-column>
        <el-table-column label="盘点数量" prop="i_iquantity"></el-table-column>
        <el-table-column label="盘盈数量" prop="i_inventory_surplus_quantity"></el-table-column>
        <el-table-column label="盘亏数量" prop="i_inventory_loss_quantity"></el-table-column>
        <el-table-column label="盘盈金额" prop="i_iwinning_amount"></el-table-column>
        <el-table-column label="盘亏金额" prop="i_inventory_loss_amount"></el-table-column>
        <el-table-column label="经办人" prop="i_ioperator"></el-table-column>
        <el-table-column label="制单人" prop="i_icreator"></el-table-column>
        <el-table-column label="所在部门" prop="i_idid"></el-table-column>
        <el-table-column label="制单时间" prop="i_idocumentpreparation_time"></el-table-column>
        <el-table-column label="逻辑删除" prop="i_iisdelete" v-if="showIdInput"></el-table-column>        
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <!-- <el-button type="text" @click="upd(scope.row)">编辑</el-button> -->
            <el-button 
            @click="upd(scope.row)" 
            type="text"
            :disabled="scope.row.i_ishen === 2" 
          >
            编辑
          </el-button>
            <el-button type="text" @click="del(scope.row)"   :disabled="scope.row.i_ishen === 2"  >删除</el-button>
          </template>
        </el-table-column>
        </el-table>
        <el-pagination v-on:size-change="handleSizeChange"
			   v-on:current-change="handleCurrentChange"
			   :current-page="currentPage"
			   :page-sizes="[10, 20, 30, 40]"
			   :page-size="pageSize"
			   layout="total, sizes, prev, pager, next, jumper">
</el-pagination>
    </div>
    <!-- 添加模态框 -->
    <!-- <el-dialog
title="新增"
:visible.sync="xsddxz"
:size="'auto'"
> -->
 <el-dialog
  title="新增"
  :visible.sync="xsddxz"
  :size="'auto'"
>
<h3>基础信息</h3>
    <el-form ref="AddForm" :model="AddForm" :rules="rules"  label-width="100px" >
<el-row>
  <el-col :span="12">
    <el-form-item label="盘点单号">
      <el-input v-model="AddForm.code" placeholder="自动获取系统编号" style="width: 200px;" disabled readonly/>
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="盘点类型" prop="type">
      <!-- <el-input v-model="AddForm.type" placeholder="请选择" style="width: 200px;"/> -->
      <el-select v-model="AddForm.type" placeholder="请选择" style="width: 100%;">
          <el-option label="初期盘点" value="1"></el-option>
          <el-option label="存货盘点" value="2"></el-option>
          <el-option label="期末盘点" value="3"></el-option>
        </el-select>
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="盘点开始时间" prop="start">
      <el-date-picker style="width: 200px;"
        v-model="AddForm.start"
        type="date"
        format="yyyy-MM-dd"
        placeholder="请选择日期">
      </el-date-picker>
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="盘点结束时间" prop="end">
      <el-date-picker style="width: 200px;"
        v-model="AddForm.end"
        type="date"
        format="yyyy-MM-dd"
        placeholder="请选择日期">
      </el-date-picker>
    </el-form-item>
  </el-col>
 <el-col :span="12">
            <el-form-item label="仓库名称" prop="ckname1">
              <el-select v-model="AddForm.ckname1" placeholder="请选择" style="width: 200px;">
                <el-option
                  v-for="option in Cklsit"
                  :key="option.w_wid"
                  :label="option.w_wname"
                  :value="option.w_wid">
                </el-option> 
              </el-select>
            </el-form-item>
          </el-col>
  <el-col :span="12">
    <el-form-item label="经办人" prop="operator">
      <el-input v-model="AddForm.operator" placeholder="请输入" style="width: 200px;" />
    </el-form-item>
 </el-col>
 <el-col :span="12">
    <el-form-item label="备注">
      <el-input v-model="AddForm.remark" placeholder="请输入" style="width: 500px;"/>
    </el-form-item>
  </el-col>
</el-row>
</el-form>
<h3>盘点明细</h3>
<div style="width: 70px;">
  <el-button type="primary" @click="MxAdd" style="font-size: 10px;">添加</el-button>
</div>


<div style="overflow-x: auto;">
  <el-table :data="xsmxdata" style="width: 100%" class="dataTable">
    <el-table-column prop="id_idid" label="序号"  ></el-table-column>
    <el-table-column prop="id_goods_name" label="货品名称"></el-table-column>
    <el-table-column prop="id_goods_code" label="货品编号"></el-table-column>
    <el-table-column prop="id_goods_model" label="规格型号"></el-table-column>
    <el-table-column prop="id_goods_unit" label="单位"></el-table-column>
    <el-table-column prop="id_goods_type" label="货品类型"></el-table-column>
    <el-table-column prop="id_book_inventory" label="账面库存"></el-table-column>
    <el-table-column prop="id_carrying_amount" label="账面金额"></el-table-column>
    <el-table-column label="入库仓位">
        <template slot-scope="scope">
          <el-select v-model="scope.row.id_position" placeholder="请选择">
            <el-option
              v-for="option in storageLocationOptions"
              :key="option.wl_wlid"
              :label="option.wl_wlname"
              :value="option.wl_wlid">
            </el-option> 
          </el-select>
        </template>
      </el-table-column>
    <el-table-column label="盘点数量">
      <template slot-scope="scope">
        <el-input v-model="scope.row.id_quantity" placeholder="请输入"></el-input>
      </template>
    </el-table-column>
    <el-table-column  label="盈亏数量">
      <template slot-scope="scope">
        {{ (scope.row.id_quantity || 0) - (scope.row.id_book_inventory || 0) }}
      </template>
    </el-table-column>
    <el-table-column label="盘点状态">  
  <template slot-scope="scope">  
    <!-- 使用内联方法调用 -->  
    {{ calculateInventoryStatus(scope.row.id_quantity, scope.row.id_book_inventory).inventoryStatus }}  
  </template>
</el-table-column>
    <!-- <el-table-column  label="盘点状态">
      <template slot-scope="scope">
        {{ (scope.row.s_DQuantitySold || 0) * (scope.row.s_DUnitPrice || 0) }}
      </template>
    </el-table-column> -->
   <el-table-column  label="参考单价">
      <template slot-scope="scope">
        <el-input v-model="scope.row.id_receipt_unitprice" placeholder="请输入"></el-input>
      </template>
    </el-table-column>
    <el-table-column  label="盈亏金额">
      <template slot-scope="scope">
        {{ (scope.row.id_receipt_unitprice || 0) * ((scope.row.id_quantity || 0) - (scope.row.id_book_inventory || 0)) }}
      </template>
    </el-table-column>
    <el-table-column  label="备注">
      <template slot-scope="scope">
        <el-input v-model="scope.row.id_remark" placeholder="请输入"></el-input>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button @click="showDispose(scope.row)" type="text">移除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- <div>
  合计&nbsp;&nbsp;&nbsp;货品总数量：{{ totalQuantity }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;总金额：{{ totalAmount }}
  </div> -->
</div>
<span slot="footer" class="dialog-footer">
  <el-button @click="xsddxz = false">取消</el-button>
  <el-button @click="saveData">保存</el-button>
</span>
</el-dialog>
<el-dialog
title="添加货品"
:visible.sync="tjhp"
:size="'auto'"
>
<div style="overflow-x: auto;">
<el-table ref="tableName" :data="rkdata" style="width: 100%" class="dataTable" @selection-change="handleSelectionChange">
  <el-table-column type="selection" width="55"></el-table-column>
  <el-table-column prop="i_IIndex" label="序号"></el-table-column>
  <el-table-column prop="i_IProductName" label="货品名称"></el-table-column>
  <el-table-column prop="i_IProductCode" label="货品编号"></el-table-column>
  <el-table-column prop="i_IModel" label="规格型号"></el-table-column>
  <el-table-column prop="i_IUnit" label="单位"></el-table-column>
  <el-table-column prop="i_IUnitPrice" label="入库单价"></el-table-column>
  <!-- <el-table-column prop="i_IQuantity" label="当前库存"></el-table-column> -->
  <el-table-column prop="i_IKuchu" label="当前库存">  
      <template slot-scope="scope">  
        <!-- 在这里进行值的计算 -->  
        {{ scope.row.i_IQuantity - scope.row.i_IYCQuantity }}  
      </template>  
    </el-table-column>
</el-table>
<span slot="footer" class="dialog-footer">
  <el-button @click="tjhp = false">取消</el-button>
  <el-button @click="hpForm">确认</el-button>
</span>  
</div>
</el-dialog>

<el-dialog
  title="编辑"
  :visible.sync="Rkxiugai"
  :size="'auto'"
>
<h3>基础信息</h3>
    <el-form ref="UpdForm" :model="UpdForm" label-width="100px" >
<el-row>
<el-col :span="12">
      <el-form-item label="编号" v-if="!isHidden">
        <el-input v-model="UpdForm.bh1" placeholder="请输入" style="width: 200px;" />
      </el-form-item>
    </el-col>
  <el-col :span="12">
    <el-form-item label="盘点单号">
      <el-input v-model="UpdForm.code" placeholder="自动获取系统编号" style="width: 200px;"/>
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="盘点类型">
      <el-select v-model="UpdForm.type" placeholder="请选择" style="width: 100%;">
          <el-option label="初期盘点" value="1"></el-option>
          <el-option label="存货盘点" value="2"></el-option>
          <el-option label="期末盘点" value="3"></el-option>
        </el-select>
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="盘点开始时间">
      <el-date-picker style="width: 200px;"
        v-model="UpdForm.start"
        type="date"
        format="yyyy-MM-dd"
        placeholder="请选择日期">
      </el-date-picker>
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="盘点结束时间">
      <el-date-picker style="width: 200px;"
        v-model="UpdForm.end"
        type="date"
        format="yyyy-MM-dd"
        placeholder="请选择日期">
      </el-date-picker>
    </el-form-item>
  </el-col>
 <el-col :span="12">
            <el-form-item label="仓库名称">
              <el-select v-model="UpdForm.ckname1" placeholder="请选择" style="width: 200px;">
                <el-option
                  v-for="option in Cklsit"
                  :key="option.w_wid"
                  :label="option.w_wname"
                  :value="option.w_wid">
                </el-option> 
              </el-select>
            </el-form-item>
          </el-col>
  <el-col :span="12">
    <el-form-item label="经办人">
      <el-input v-model="UpdForm.operator" placeholder="请输入" style="width: 200px;" />
    </el-form-item>
 </el-col>
 <el-col :span="12">
    <el-form-item label="备注">
      <el-input v-model="UpdForm.remark" placeholder="请输入" style="width: 500px;"/>
    </el-form-item>
  </el-col>
</el-row> 
</el-form>
<span slot="footer" class="dialog-footer">
  <el-button @click="Rkxiugai = false">取消</el-button>
  <el-button @click="rksaveData1">确认</el-button>
</span> 
</el-dialog>
<el-dialog
  title="审核"
  :visible.sync="shenhe"
  :size="'auto'"
>
<el-form ref="ShenForm" :model="ShenForm" label-width="100px" >
  <el-row>
    <el-col :span="12">
      <el-form-item label="编号" v-if="!isHidden">
        <el-input v-model="ShenForm.bh1" placeholder="请输入" style="width: 200px;" />
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="审核结果">
        <el-radio-group v-model="ShenForm.jieguo">
          <el-radio label="通过">通过</el-radio>
          <el-radio label="驳回">驳回</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-col>
  </el-row>
</el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="shenhe= false">取消</el-button>
      <el-button @click="ShenData">确认</el-button>
      
    </span>
</el-dialog>
    </div>
</template>

<script>
import axios from 'axios';
import $http from '../router/base.js';
export default {
    data(){
        return{
            data:[],
            xsmxdata:[],//盘点明细的数据
            shenhe:false,//审核的模态框
            tjhp:false,//盘点明细添加货品
            isHidden: true, // 控制文本框显示与隐藏的变量
            showIdInput: false,
            rkdata:[],//入库的货品
            xsddxz:false,//新增模态框
            Rkxiugai:false,//编辑模态框
            Cklsit:[],//仓库的下拉框
            storageLocationOptions:[],//库位的下拉框
            targetPage: "",
            totalRecords: 10,
            currentPage: 1,
            totalPages: 10,
            pageSize: 10,
            search:{
                code:'',
                result:'',
                type:'',
            },
            AddForm:{
              code:'',
              type:'',
              start:'',
              end:'',
              ckname1:'',
              operator:'',
              remark:'',
            },
            UpdForm:{
              bh1:0,
              code:'',
              type:'',
              start:'',
              end:'',
              ckname1:'',
              operator:'',
              remark:'',
            },
             ShenForm:{//审核
          bh1:'',
          jieguo:'',
        },

        rules: {
  
          type: [
    { required: true, message: '请选择类型', trigger: 'blur' },
  ],
  start: [
    { required: true, message: '请选择开始时间', trigger: 'blur' },
  ],
  end: [
    { required: true, message: '请选择结束时间', trigger: 'blur' },
  ],
  ckname1: [
    { required: true, message: '请选择仓库', trigger: 'blur' },
  ],
  operator: [
    { required: true, message: '请输入经办人', trigger: 'blur' },
  ],
  

},
    
    //编号
     orderNumber:'',
            }
            },
            methods: {
              getStatusColor(status) {
      const statusColorMap = {
        '2': 'green',
        '1': 'red',
    
      };
      return statusColorMap[status];
    },
    generateCode() {
      // 生成随机大写字母
      const randomLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));

      // 生成当前日期
      const currentDate = new Date().toISOString().slice(0, 10).replace(/-/g, '');

      // 生成4个随机数字
      const randomDigits = Math.floor(1000 + Math.random() * 9000);

      // 组合成编号
      return randomLetter + currentDate + randomDigits;
    },
            //查询
        fill(){
        axios.get('http://localhost:5084/api/Inventory/FenYe',{
            params: {
            pageSize: this.pageSize,
            currentPage: this.currentPage
       }
        })
          .then(res => {
            this.data = res.data;
            this.totalRecords = res.data.length;
            this.totalPages = Math.ceil(this.totalRecords / this.pageSize); // 计算总页数
          })
       },
       //模糊查询
      query() {
  // 查询数据逻辑
  const { code, result,type } = this.search;
  axios.get('http://localhost:5084/api/Inventory/FenYe', {
    params: {
      pageSize: this.pageSize,
      currentPage: this.currentPage,
      code: code,
      result: result,
      type: type,
    } 
  }).then((response) => {
    this.data = response.data;
  }).catch((error) => {
    console.log(error);
  });
},
//点击按钮删除
  del: function (sale) {
    if (confirm("确定删除吗")) {
        var t = this;
        axios.put(`http://localhost:5084/api/Inventory/UpdIsDelete?id=${sale.i_iid}&&isDeleted=${false}`)
            .then(function (response) {
                // 根据后台返回的结果处理相应逻辑
                if (response.data > 0) {
                    alert("删除成功");
                    t.fill(); // 如果删除成功，重新加载数据
                } else {
                    alert("删除失败");
                }
            })
            .catch(function (error) {
                console.error(error);
                alert("删除失败");
            });
    }
},
//盘点修改
      upd(row){
        this.Rkxiugai=true;
        this.Ckqu();
        
        this.UpdForm.bh1=row.i_iid;
         this.UpdForm.code=row.i_icode;
         this.UpdForm.type=row.i_itype;
         this.UpdForm.start=row.i_istart_time;
         this.UpdForm.end=row.i_iend_time;
         this.UpdForm.ckname1=row.i_iwid;
         this.UpdForm.operator=row.i_ioperator;
         this.UpdForm.remark=row.i_iremark;
      },
     // 修改的数据保存到数据库
      rksaveData1(){
        $http.put("api/Inventory/Upd", {
          
          i_iid:this.UpdForm.bh1,
          i_icode:this.UpdForm.code,
          i_itype:  this.UpdForm.type,
          i_istart_time:  this.UpdForm.start,
          i_iend_time: this.UpdForm.end,
          i_iwid: this.UpdForm.ckname1,
          i_ioperator:this.UpdForm.operator,
          i_iremark:this.UpdForm.remark,
  }).then(res => {
    if (res) {
      this.$message({
        message: '修改成功！',
        type: 'success'
      });

      this.Rkxiugai = false;
      this.fill(); // 重新填充销售机会列表
    }
  })
  .catch(err => {
    this.$message({
      message: '修改失败！',
      type: 'error'
    });
  });
      },
 saveData(){//盘点和盘点明细的添加的保存
  this.$refs.AddForm.validate((valid) => {
    if (valid) {
        // 生成编号
 this.orderNumber = this.generateCode();
 this.saveForm();
      this.savea();
      this.xsddxz=false;
      this.fill();
      //this.Qu();
    } else {
      // 表单验证失败，可以在这里进行相应的提示或处理
    }
  });
    
      //this.Qu();
    },
    // Qu(){//总行数
    //     $http.get('api/InboundS/Qu', {
    // }).then((response) => {
    //   this.rows = response.length;
     
    // }).catch((error) => {
    //   console.log(error);
    // });
    //    },
    //盘点明细表的添加
    savea() { 
 // 遍历数的每一行数据
    this.xsmxdata.forEach(row => {
      const cw=row.id_position.toString();
      const inventoryStatusObj = this.calculateInventoryStatus(row.id_quantity, row.id_book_inventory);  
      const inventoryStatus = inventoryStatusObj.inventoryStatus; // 如果你还需要显示的状态  
      const inventoryStatusValue = inventoryStatusObj.actualValue; // 获取整数值  
      const postData = {
         id_goods_name: row.id_goods_name,
    id_goods_code: row.id_goods_code,
    id_goods_model: row.id_goods_model,
    id_goods_unit: row.id_goods_unit,
    id_goods_type: row.id_goods_type,
    id_book_inventory: row.id_book_inventory,
    id_carrying_amount: row.id_carrying_amount,
    id_position:cw,
    id_quantity:row.id_quantity,
    id_profit_and_loss_quantity:(row.id_quantity || 0) - (row.id_book_inventory || 0),
    id_i_state: inventoryStatusValue,
    id_receipt_unitprice:row.id_receipt_unitprice,
    id_profit_and_loss_amount:(row.id_receipt_unitprice || 0) * ((row.id_quantity || 0) - (row.id_book_inventory || 0)),
    id_remark:row.id_remark,
    i_icode:this.orderNumber,
      };
      // 发送每一行数据到服务器进行添加
      $http.post("api/PDinventory_details", postData)
        .then(res => {
          if (res) {
            this.$message({
              message: '添加成功！',
              type: 'success'
            });
          } else {
            this.$message({
              message: '添加失败！',
              type: 'error'
            });
          }            
        })
        .catch(error => {
          console.error('添加失败:', error);
          this.$message.error('添加失败，请稍后重试！');
        });
    });
},
    saveForm() {//盘点表的添加
const ck=this.AddForm.ckname1.toString();
$http.post("api/Inventory", {
  i_icode: this.orderNumber,
  i_iresult:this.surplusandloss,
  i_iwid: ck,
  i_itype: this.AddForm.type,
  i_istart_time: this.AddForm.start,
  i_iend_time: this.AddForm.end,
  i_ioutbound_status:1,
  i_ientry_status: 1,
  i_igoods: this.concatenatedProductNames,
  i_iquantity: this.totalQuantity,
  i_inventory_surplus_quantity: this.totalsurplusandloss,
  i_inventory_loss_quantity: -(this.totalsurplusandloss),
  i_inventory_amount: this.totalAmount,
  i_iwinning_amount: this.totalsurplusandlossamount, // 使用正确的日期变量
  i_inventory_loss_amount: -(this.totalsurplusandlossamount), 
  i_ioperator: this.AddForm.operator, 
  i_icreator: 1, 
  i_idid:1,
  i_idocumentpreparation_time:new Date(),
  i_icreateuser:1,
  i_icreatetime:new Date(),
  i_iupdateuser:null,
  i_iupdatetime:null,
  i_iremark:this.AddForm.remark,
  i_ishen:1,
})
.then(res => {
  if (res) { // 注意这里应该判断 res.data 而不是 res
    this.$message({
      message: '添加成功！',
      type: 'success'
    });
    this.fill();
      //this.Qu();
  } else {
    this.$message({
      message: '添加失败！',
      type: 'error' // 应该是 error 类型
    });
  }
})
.catch(error => {
  console.error('请求失败:', error);
  this.$message.error('请求失败，请稍后重试！');
});
},
//入库审核
        ShenData(){
        $http.put(`api/Inventory?to=${this.ShenForm.jieguo}`, {
          i_iid: this.ShenForm.bh1,
         
  }).then(res => {
    if (res) {
      this.$message({
        message: '审核成功！',
        type: 'success'
      });

      this.shenhe = false;
      this.fill(); // 重新填充销售机会列表
    }
  })
  .catch(err => {
    this.$message({
      message: '审核失败！',
      type: 'error'
    });
  });
      },
      handleShen(){
          this.shenhe=true;
          this.ShenForm.bh1=this.selectedPOIndex;
      },
      handleCang() {
    this.$router.push({ path: '/warehouse' });
  },
    //   handleChe(){
    //     //this.ShenForm.bh1=this.selectedPOIndex;
    //      if (confirm("确定撤回吗？")) { 
    //     var t = this;
    //     axios.put(`http://localhost:5084/api/Inventory/UpdShen?id=${this.selectedPOIndex}&&shen=${1}`)
    //         .then(function (response) {
    //             // 根据后台返回的结果处理相应逻辑
    //             if (response.data > 0) {
    //                 alert("撤回成功");
    //                 t.fill(); // 如果删除成功，重新加载数据
    //             } else {
    //                 alert("撤回失败");
    //             }
    //         })
    //         .catch(function (error) {
    //             console.error(error);
    //             alert("撤回失败");
    //         });
    // }
    //   },
       // 处理复选框选中事件
      handleSelectionChangeDel(selection) {
  this.selectedIds = selection.map(item => item.i_iid);
  if (selection && selection.length > 0) {
        const selectedRow = selection[0]; // 获取选中的第一行数据
        this.selectedPOIndex = selectedRow.i_iid; // 获取选中行的编号
      } else {
        this.selectedPOIndex = ''; // 如果没有选中行，则清空选中行的编号
      }
       console.log("1"+this.selectedIds);
       console.log("2"+this.selectedPOIndex);
},
//盘点明细添加货品确认
     hpForm() {
      const selectedRows = this.$refs.tableName.selection; // 获取所有选中的行数据
    // 检查是否至少选择了一行
    if (selectedRows.length > 0) {
      // 遍历选中的每一行数据
      selectedRows.forEach(row => {
        const currentInventory = row.i_IQuantity - row.i_IYCQuantity;
        // 将选中行数据添加到显示数据数组中
        this.xsmxdata.push({
          id_idid: this.xsmxdata.length + 1, // 序号为当前数组长度加1
          id_goods_name: row.i_IProductName,
          id_goods_code: row.i_IProductCode,
          id_goods_model: row.i_IModel,
          id_goods_unit: row.i_IUnit,
          id_goods_type: row.i_IProductType,
          id_book_inventory: currentInventory,
          id_carrying_amount:row.i_IUnitPrice,
          id_position:null,
          id_quantity:null,
          id_profit_and_loss_quantity:null,
          id_receipt_unitprice:null,
          id_profit_and_loss_amount:null,
          id_remark:null
        });
      });
      
      // 关闭弹窗
      this.tjhp = false;
    } else {
      // 提示用户至少选择一行数据
      this.$message.warning('请至少选择一行数据！');
    }
  },
  handleSelectionChange(selection) {
    this.selectedRows = selection;
  },
  calculateInventoryStatus(idQuantity, idBookInventory) {  
      let profitLossQuantity = (idQuantity || 0) - (idBookInventory || 0);  
      let inventoryStatus = '';  
      let actualValue = 0;  
  
      if (profitLossQuantity < 0) {  
        inventoryStatus = '盘亏';  
        actualValue = 1;  
      } else if (profitLossQuantity > 0) {  
        inventoryStatus = '盘盈';  
        actualValue = 2;  
      } else {  
        inventoryStatus = '无盈亏';  
        actualValue = 3;  
      }  
      // 只返回盘点状态，如果需要实际值可以在组件内部处理  
      //return inventoryStatus;  
      return {  
    inventoryStatus: inventoryStatus,  
    actualValue: actualValue  
  };
    },
 //库位的下拉框
       Wqu(){
        axios.get('http://localhost:5084/api/Warehouselocation/Wqu',{              
            }).then((response)=>{
               this.storageLocationOptions=response.data;
              
            }).catch((error)=>{
               console.log(error);
              
            })
       },
//仓库名称的下拉框
       Ckqu(){
        axios.get('http://localhost:5084/api/Warehouse/Wqu',{              
            }).then((response)=>{
               this.Cklsit=response.data;
              
            }).catch((error)=>{
               console.log(error);
              
            })
       },
       handleAdd(){
      this.xsddxz=true;   
      this.Ckqu();
      this.Wqu();
    },
    MxAdd(){
      this.tjhp=true;
         this.HoupQu();
    },
    //入库明细查询
    HoupQu(){
      axios.get('http://localhost:5084/api/Inventorydetails/Qu',{              
          }).then((response)=>{
             this.rkdata=response.data;
          }).catch((error)=>{
             console.log(error);
          })
    },
//重置按钮实现
  clear() {
    // 清空搜索条件
  this.search.Name = '';
  this.search.Status = '';
  // 重新调用查询方法，以获取所有数据
  this.fill();
  },
       handleSizeChange: function (size) {
				console.log(size);
				this.pageSize = size;
				this.fill();
  },
  handleCurrentChange: function (cpage) {
				console.log(cpage);
				this.currentPage = cpage;
				this.fill();
    },
       },
       mounted: function () {
    this.fill();
 },
 computed: {
    totalQuantity() {
      // 计算盘点数量的总和
      return this.xsmxdata.reduce((total, item) => total + (parseFloat(item.id_quantity) || 0), 0);
    },
    concatenatedProductNames() {
      return this.xsmxdata
        .map(item => `${item.id_goods_name}`) // 将每个货品名称转换为所需格式
        .join('，'); // 使用逗号拼接所有转换后的货品名称
    },
    totalAmount() {
      // 计算金额的总和
      return this.xsmxdata.reduce((total, item) => total + ((item.id_quantity || 0) * (item.id_receipt_unitprice || 0)), 0);
    },
     totalsurplusandloss() {
      // 计算盈亏数
      return this.xsmxdata.reduce((total, item) => total + ((item.id_quantity || 0) - (item.id_book_inventory || 0)), 0);
    },
     surplusandloss() {
      // 计算盈亏数
      let ff = this.xsmxdata.reduce((total, item) => total + ((item.id_quantity || 0) - (item.id_book_inventory || 0)), 0);
      if(ff>0||ff<0){
        return 2;
      }else if(ff=0){
        return 1;
      }else{
        return null;
      }
    },
  totalsurplusandlossamount() {
      // 计算盈亏金额
      return this.xsmxdata.reduce((total, item) => total + (item.id_receipt_unitprice || 0) * ((item.id_quantity || 0) - (item.id_book_inventory || 0)), 0);
    },
  },
}
</script>

<style scoped>
.cz
{
margin-right: 20px; 
width: 80px; 
height: 40px; 
background-color: white; 
color: black;
border-color: #C1C1C1;
margin-left: 20px;
}
.cx
{
   color: white;
   background-color: #45B984; 
}
.bian
{
    margin:20px;
}
 .el-dialog {
    max-height: 70%;
  }
  .xin{
 
  height:1px;
  color: red;
  position: relative;
  left: 19px; /* 根据需要调整星号的水平位置 */
  top: 32px; /* 根据需要调整星号的垂直位置 */
}
.xinx{
  position: relative;
  left: 0px; /* 根据需要调整星号的水平位置 */
  top: 20px; /* 根据需要调整星号的垂直位置 */
}
</style>